package cn.tit.ias.service.impl;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.tit.ias.aop.MethodLog;
import cn.tit.ias.entity.AssetInfo;
import cn.tit.ias.entity.UserInfo;
import cn.tit.ias.mapper.AssetInfoMapper;
import cn.tit.ias.mapper.DepartInfoMapper;
import cn.tit.ias.mapper.DicProfitLossInfoMapper;
import cn.tit.ias.mapper.StoreInfoMapper;
import cn.tit.ias.mapper.UserInfoMapper;
import cn.tit.ias.service.AssetInfoService;
import cn.tit.ias.util.handlexcel.easyexcel.EasyExcelHanderUtil;
import cn.tit.ias.vo.InventoryVo;

@Service
public class AssetInfoServiceImpl implements AssetInfoService {
	
	private static final String INVENTORY_BATCH_RUN_STATUS = "运行";
	private static final String INVENTORY_BATCH_OVER_STATUS = "结束";
	@Autowired
	AssetInfoMapper assetinfoMapper;
	@Autowired
	DepartInfoMapper departInfoMapper;
	@Autowired
	DicProfitLossInfoMapper profitLossMapper;
	@Autowired
	StoreInfoMapper storeInfoMapper;
	@Autowired
	UserInfoMapper userInfoMapper;

	/************** 隔山海 ******************/
	@Override
	public List<List<Object>> packageExportData(List<AssetInfo> assets) {
		List<List<Object>> packageData = new ArrayList<>();
		for (int i = 0; i < assets.size(); i++) {
			List<Object> row = new ArrayList<>();
			AssetInfo asset = assets.get(i);
			row.add(asset.getAssetNum());
			if (asset.getStoreNum() != null) {
				row.add(storeInfoMapper.getObject(asset.getStoreNum()).getStoreName());
			} else {
				row.add("无");
			}
			if (asset.getDepartNum() != null) {
				row.add(departInfoMapper.getObject(asset.getDepartNum()).getDepartName());
			} else {
				row.add("无");
			}
			row.add(asset.getAssetDocumentNum());
			row.add(asset.getAssetName());
			row.add(asset.getAssetModel());
			row.add(asset.getAssetPrice().toString());
			row.add(asset.getAssetFactory());
			row.add(asset.getAssetBuyDate());
			row.add(asset.getAssetTakePeople());
			row.add(asset.getAssetRemrk());
			if (asset.getDicProfitLossNum() != null) {
				row.add(profitLossMapper.getObject(asset.getDicProfitLossNum()).getDicProfitLossName());
			} else {
				row.add("无");
			}
			packageData.add(row);
		}
		return packageData;
	}

	@Override
	public List<String> listAssetInfoNumsByStore(int storeNum) {
		return assetinfoMapper.listAssetInfoNumsByStore(storeNum);
	}

	@Override
	@MethodLog(name = "资产信息模块", option = "添加一条资产信息")
	public int addObject(AssetInfo entity) {
		return assetinfoMapper.addObject(entity);
	}

	@Override
	@MethodLog(name = "资产信息模块", option = "删除资产")
	public int deleteObject(Serializable id) {
		return assetinfoMapper.deleteObject(id);
	}

	@Override
	@MethodLog(name = "资产信息模块", option = "修改资产信息")
	public int updateObject(AssetInfo entity) {
		return assetinfoMapper.updateObject(entity);
	}

	@Override
	// @MethodLog(name = "资产信息模块",option = "根据资产编号查询资产信息")
	public AssetInfo getObject(Serializable id) {
		return assetinfoMapper.getObject(id);
	}

	// 创建批次号
	@Override
	// @MethodLog(name = "盘点模块",option = "单个创建批次号")
	public void createBatch(String Batch, String assetNum) {
		AssetInfo asset = new AssetInfo();
		try {
			asset = assetinfoMapper.getObject(assetNum);
		} catch (Exception e) {
			asset = null;
		}
		if (asset != null) {
			List<Map<String, Object>> newBranchAssets = new ArrayList<Map<String, Object>>();
			Map<String, Object> newBranchAsset = new HashMap<>();
			newBranchAsset.put("assetNum", asset.getAssetNum());
			newBranchAsset.put("inventoryBatch", Batch);
			newBranchAsset.put("inventoryStatusId", 0);
			newBranchAsset.put("inventoryDate", "001-01-01");
			newBranchAsset.put("departNum", asset.getDepartNum());
			newBranchAsset.put("assetTakePeople", asset.getAssetTakePeople());
			newBranchAsset.put("dicProfitLossNum", asset.getDicProfitLossNum());
			newBranchAsset.put("storeNum", asset.getStoreNum());
			newBranchAssets.add(newBranchAsset);
			// 盘点表中初始化新批次号的盘点信息
			assetinfoMapper.createBatchBybranch(newBranchAssets);
		}
	}

	@Override
	// @MethodLog(name = "盘点模块",option = "批量创建批次号")
	public void createBatchByBranch(String batch,String departNum, List<AssetInfo> assetInfos) {
		List<Map<String, Object>> newBranchAssets = new ArrayList<>();
		Iterator<AssetInfo> iterator = assetInfos.iterator();
		while (iterator.hasNext()) {
			Map<String, Object> newBranchAsset = new HashMap<>();
			AssetInfo temp = iterator.next();
			newBranchAsset.put("inventoryBatch", batch);
			newBranchAsset.put("assetNum", temp.getAssetNum());
			newBranchAsset.put("inventoryStatusId", 0);
			newBranchAsset.put("inventoryDate", "001-01-01");
			newBranchAsset.put("departNum", temp.getDepartNum());
			newBranchAsset.put("assetTakePeople", temp.getAssetTakePeople());
			newBranchAsset.put("dicProfitLossNum", temp.getDicProfitLossNum());
			newBranchAsset.put("storeNum", temp.getStoreNum());
			newBranchAssets.add(newBranchAsset);
		}
		// 盘点表中初始化新批次号的盘点信息
		assetinfoMapper.createBatchBybranch(newBranchAssets);
		// 创建开关
		assetinfoMapper.createSwitch(batch,departNum);
	}

	// 部门编号获取最大批次号
	@Override
	public String getMaxBatch(String departNum) {
		return assetinfoMapper.getMaxBatch(departNum);
	}

	@Override
	public List<String> getAllBatchByDepart(String departNum) {
		return assetinfoMapper.getAllBatchByDepart(departNum);
	}

	@Override
	public Map<String, Object> getAssetByBatch(int offset, int limit, String batch) {
		Map<String, Object> resultSet = new HashMap<>();
		List<Map<String, Object>> asset = new ArrayList<>();
		int total = 0;
		boolean isPagination = true;
		if (offset < 0 || limit < 0)
			isPagination = false;
		try {
			if (isPagination) {
				asset = assetinfoMapper.getAssetByBatch(batch, offset, limit);
				// System.out.println("资产+"+asset);
				if (asset != null) {
					PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(asset);
					total = assetinfoMapper.getAssetByBachCount(batch);
				} else {
					System.out.println("空列表");
					asset = new ArrayList<>();
				}
			} else {
				asset = assetinfoMapper.getAssetByBatch(batch, offset, limit);
				if (asset != null) {
					total = assetinfoMapper.getAssetByBachCount(batch);
				} else {
					asset = new ArrayList<>();
				}
			}
		} catch (Exception e) {

		}
		resultSet.put("data", asset);
		resultSet.put("total", total);
		return resultSet;
	}

	@Override
	public Map<String, Object> getAssetByBatch_v1(int offset, int limit, String batch) {
		Map<String, Object> resultSet = new HashMap<>();
		List<Map<String, Object>> asset = new ArrayList<>();
		int total = 0;
		boolean isPagination = true;
		if (offset < 0 || limit < 0)
			isPagination = false;
		try {
			if (isPagination) {
				// 添加分页条件,分页查询
				PageHelper.offsetPage(offset, limit);
				asset = assetinfoMapper.getAssetByBatch_v1(batch);
				 //System.out.println("资产+"+asset);
				// 判断查询结果是否为空
				if (asset != null) {
					PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(asset);
					total = (int) pageInfo.getTotal();
				} else {
					System.out.println("空列表");
					asset = new ArrayList<>();
				}
			} else {
				// 条件正确不用分页
				asset = assetinfoMapper.getAssetByBatch_v1(batch);
				if (asset != null) {
					total = asset.size();
				} else {
					asset = new ArrayList<>();
				}
			}
		} catch (Exception e) {

		}
		resultSet.put("data", asset);
		resultSet.put("total", total);
		return resultSet;
	}
	
	@Override
	// @MethodLog(name = "盘点模块",option = "删除盘点信息")
	public int deleteinventory(String assetnum, String Batch) {
		return assetinfoMapper.deleteinventory(assetnum, Batch);
	}

	@Override
	public List<AssetInfo> listAllObject(Object... param) {
		return assetinfoMapper.listAllObject();
	}


	@Override
	public List<Map<String, Object>> listInventoryStatusObj() {
		return assetinfoMapper.listInventoryStatusObj();
	}

	@Override
	public Map<String, Object> getInventoryStatusObjByInventoryStatusId(int id) {
		return assetinfoMapper.getInventoryStatusObjByInventoryStatusId(id);
	}

	@Override
	public Map<String, Object> getInventoryStatusObjByInventoryStatusName(String name) {
		return assetinfoMapper.getInventoryStatusObjByInventoryStatusName(name);
	}

	@Override
	// @MethodLog(name = "盘点模块",option = "修改盘点记录")
	public int updateInventory(Map<String, Object> inventory) {
		/* 写入盘点时间 */
		Date now = new Date();
		/* 将日期格式化 */
		SimpleDateFormat normalize = new SimpleDateFormat("yyyy-MM-dd");
		String time = normalize.format(now);
		inventory.put("inventoryDate", time);
		System.out.println(inventory);
		return assetinfoMapper.updateInventory(inventory);
	}

	@Override
	public List<AssetInfo> listObjectByCondition(AssetInfo assetInfo) {
		return assetinfoMapper.listObjectByCondition(assetInfo);
	}

	@Override
	// @MethodLog(name = "资产信息模块",option = "查询资产信息")
	public Map<String, Object> listObjectByConditionByPage(int offset, int limit, AssetInfo assetInfo) {
		Map<String, Object> resultSet = new HashMap<>();
		List<AssetInfo> assets = null;
		int total = 0;
		boolean isPagination = true;
		if (offset < 0 || limit < 0)
			isPagination = false;
		try {
			if (isPagination) {
				PageHelper.offsetPage(offset, limit);
				assets = assetinfoMapper.listObjectByCondition(assetInfo);
				if (assets != null) {
					PageInfo<AssetInfo> pageInfo = new PageInfo<>(assets);
					total = (int) pageInfo.getTotal();
					System.out.println(total);
				} else {
					assets = new ArrayList<>();
				}
			} else {
				assets = assetinfoMapper.listObjectByCondition(assetInfo);
				if (assets != null) {
					total = assets.size();
				} else {
					assets = new ArrayList<>();
				}
			}
		} catch (Exception e) {

		}
		resultSet.put("data", assets);
		resultSet.put("total", total);
		return resultSet;
	}

	/* 获取存放地某存放地的所有资产编号 */
	@Override
	public List<String> listAssetNumByBatchStoreNum(String Batch, int StoreNum) {
		return assetinfoMapper.listAssetNumByBatchStoreNum(Batch, StoreNum);
	}

	/** 针对部门异常-通过批次号和扫描地编号获取所有部门异常盘点信息 */
	@Override
	public List<String> listAssetNumByBatchSpanAdress(String Batch, int spanAdress) {
		return assetinfoMapper.listAssetNumByBatchSpanAdress(Batch, spanAdress);
	}

	@Override
	public Object getInventoryParameterByCondition(Map<String, Object> condition) {
		return assetinfoMapper.getInventoryParameterByCondition(condition);
	}

	@Override
	public Map<String, Object> getInventoryObjByCondition(Map<String, Object> condition) {
		return assetinfoMapper.getInventoryObjByCondition(condition);
	}

	@Override
	public Map<String, Object> getSwitch(String Batch) {
		return assetinfoMapper.getSwitch(Batch);
	}

	@Override
	public int closeSwitch(String Batch) {
		return assetinfoMapper.closeSwitch(Batch);
	}

	@Override
	public int listInventoryAssetNumberByCondition(Map<String, Object> condition) {
		return assetinfoMapper.listInventoryAssetNumberByCondition(condition);
	}

	@Override
	public int getCountByConditon(AssetInfo assetInfo) {

		return assetinfoMapper.getCountByConditon(assetInfo);
	}

	@Override
	public Map<String, Object> listInventoryBatchInfoByDepart(String departNum,Integer offset,Integer limit) {
		Map<String, Object> result = new HashMap<>();
		int total = 0;
		boolean isPagination = true;
		List<Map<String, Object>> batchs = new ArrayList<>();
		if (offset < 0 || limit < 0)
			isPagination = false;
		try {
			if(isPagination)// 判断是否分页
				PageHelper.offsetPage(offset, limit);
			// 查询出选择部门的盘点批次信息
			batchs = assetinfoMapper.listInventoryBatchInfoByDepart(departNum);
			if(batchs != null){
				PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(batchs);
				total = (int) pageInfo.getTotal();
				// 遍历将盘点批次的盘点运行状态码转成 0：结束 1：运行；将用户账户显示为用户名称
				for (int i = 0; i < batchs.size(); i++) {
					int status = (int) batchs.get(i).get("runStatus");
					if (status == 1) {
						batchs.get(i).put("runStatus", INVENTORY_BATCH_RUN_STATUS);
					} else {
						batchs.get(i).put("runStatus", INVENTORY_BATCH_OVER_STATUS);
					}
					String userCount = (String) batchs.get(i).get("createUser");
					String userName = "";
					try {
						userName = userInfoMapper.getObject(userCount).getUserName();
					} catch (Exception e) {
						userName = "创建者不存在";
					}
					batchs.get(i).put("createUser", userName);
				}
			}
			
		} catch (Exception e) {
		
		}
		result.put("total", total);
		result.put("data", batchs);
		return result;
	}

	@Override
	public Map<String, Object> getInventoryBatchInfoByBatch(String batch) {
		return assetinfoMapper.getInventoryBatchInfoByBatch(batch);
	}

	@Override
	public int addInventoryBatchInfo(Map<String, Object> batchInfo) {
		return assetinfoMapper.addInventoryBatchInfo(batchInfo);
	}

	@Override
	public int deleteInventoryBatchInfo(String Batch) {
		assetinfoMapper.closeSwitch(Batch);
		return assetinfoMapper.deleteInventoryBatchInfo(Batch);
	}

	@Override
	public int updateInventoryBatchInfo(Map<String, Object> batchInfo) {
		return assetinfoMapper.updateInventoryBatchInfo(batchInfo);
	}

	@Override
	public int listInventoryAssetNumberByCondition_v1(Map<String, Object> condition) {
		return assetinfoMapper.listInventoryAssetNumberByCondition_v1(condition);
	}

	@Override
	public Map<String, Object> getSwitch_v1(Map<String, Object> condition) {
		return assetinfoMapper.getSwitch_v1(condition);
	}

	@Override
	@MethodLog(name = "资产信息模块", option = "导出资产信息")
	public void exportAssetInfoByCondition(String key, String value, UserInfo loginUser,Integer excel_id,HttpServletRequest request,HttpServletResponse response) {
		
		// 经过处理后要导出的数据源
		List<Map<String, Object>> listExportAssets = new ArrayList<>();
		// 查询的条件
		AssetInfo assetInfo = new AssetInfo();
		assetInfo.setDepartNum(loginUser.getDepartNum());
		// 查询出未处理的数据
		List<AssetInfo> listAssetInfos = new ArrayList<>();
		if (key == null && "".equals(key))
			return;
		if ("所有".equals(key)) {
			listAssetInfos = assetinfoMapper.listObjectByCondition(assetInfo);
		}
		if (!"".equals(value) && value != null) {
			if ("资产编号".equals(key)) {
				assetInfo.setAssetNum(value);
				listAssetInfos = assetinfoMapper.listObjectByCondition(assetInfo);
			} else if ("资产名称".equals(key)) {
				assetInfo.setAssetName(value);
				listAssetInfos = assetinfoMapper.listObjectByCondition(assetInfo);
			} else if ("领用人".equals(key)) {
				assetInfo.setAssetTakePeople(value);
				listAssetInfos = assetinfoMapper.listObjectByCondition(assetInfo);
			} else if ("存放地".equals(key)) {
				int storeNum = storeInfoMapper.getStoreByName(value).getStoreNum();
				assetInfo.setStoreNum(storeNum);
				assetinfoMapper.listObjectByCondition(assetInfo);
			} else if ("部门".equals(key)) {
				String departNum1 = departInfoMapper.getDepartByName(value).getDepartNum();
				assetInfo.setDepartNum(departNum1);
				listAssetInfos = assetinfoMapper.listObjectByCondition(assetInfo);
			} else if ("损溢类型".equals(key)) {
				int profitLossNum = profitLossMapper.getDicProfitLossByName(value).getDicProfitLossNum();
				assetInfo.setDicProfitLossNum(profitLossNum);
				listAssetInfos = assetinfoMapper.listObjectByCondition(assetInfo);
			}
		}
		Iterator<AssetInfo> iterator = listAssetInfos.iterator();
		while (iterator.hasNext()) {
			Map<String, Object> map = new HashMap<>();
			AssetInfo temp;
			temp = iterator.next();
			map.put("assetNum", temp.getAssetNum());
			map.put("assetName", temp.getAssetName());
			map.put("assetModel", temp.getAssetModel());
			map.put("assetPrice", temp.getAssetPrice());
			map.put("assetFactory", temp.getAssetFactory());
			map.put("assetDocumentNum", temp.getAssetDocumentNum());
			map.put("assetBuyDate", temp.getAssetBuyDate());
			map.put("assetTakePeople", temp.getAssetTakePeople());
			map.put("assetRemrk", temp.getAssetRemrk());
			if (temp.getStoreNum() == null) {
				map.put("store", "无");
			} else {
				map.put("store", storeInfoMapper.getObject(temp.getStoreNum()).getStoreName());
			}
			if (temp.getDepartNum() == null && temp.getDepartNum() == "") {
				map.put("depart", "无");
			} else {
				map.put("depart", departInfoMapper.getObject(temp.getDepartNum()).getDepartName());
			}
			if (temp.getDicProfitLossNum() == null) {
				map.put("profitLoss", "无");
			} else {
				map.put("profitLoss", profitLossMapper.getObject(temp.getDicProfitLossNum()).getDicProfitLossName());
			}
			listExportAssets.add(map);
		}
			// 表格中添加的非列表参数
			Map<String, Object> map1 = new HashMap<String, Object>();
			// 表头名称
			map1.put("depart","计算机工程系");
			// excel模板表路径
			String templateFileName = request.getSession().getServletContext().getRealPath("/")
							+File.separator+ "file"+File.separator+"download"+File.separator+"assetInfo.xlsx";
			// 查询名称返回的结果
			EasyExcelHanderUtil.ExcelTemplate(templateFileName,excel_id, listExportAssets, map1, request, response);
	}

//	重构-根据部门编号、存放地编号获取已盘点/未盘点/部门异常/存放地异常
	@Override
	public List<InventoryVo> getScanList(String departNum, String storeName,Integer status) {
		Integer storeNum = storeInfoMapper.getStoreByName(storeName).getStoreNum();
		return assetinfoMapper.getScanList(departNum,storeNum,status);
	}

}
